<?php

namespace addons\hlapp\controller;
use addons\hlapp\dto\Result;
use addons\hlapp\model\HlappEvaluateSendLogs;
use addons\hlapp\model\HlappMember;
use addons\hlapp\model\HlappPart;
use addons\hlapp\model\HlappProject;
use addons\hlapp\model\HlappProjectEvaluate;
use addons\hlapp\model\HlappProjectSolve;
use addons\hlapp\model\HlappProjectStatus;
use addons\hlapp\model\HlappTypeStage;
use addons\hlapp\service\PushService;
use addons\hlapp\service\TypeStageService;
use function Composer\Autoload\includeFile;
use think\Db;
use think\Exception;
use think\facade\Session;

class Wap extends Common
{
    public $isWexinLogin=true; //微信页面需要开启

    /**
     *  登记手机号页面
     * @return mixed|void
     */
    public function index(){
        return $this->fetch();
    }

    /**
     * 甲方评价界面
     */
    public function evaluate(){
//        $statusId = $_GET["statusId"];
        $eid = $_GET["eid"]; //评价id
        $evaluate = HlappProjectEvaluate::get($eid);
        $p = new HlappProject();
        //页面不存在
        if(!$evaluate['projectId']){
            return $this->fetch('Default/noPage');
        }
        $project = $p->getProject($evaluate['projectId']);
        //  查找评价信息

        $evaluateTemplate= HlappProjectEvaluate::getEvaluateTemplate($project->name,$p->getStageAttr($evaluate['stage']));
//        $evaluateOption=HlappProjectEvaluate::$evaluateOption[$evaluate['stage']];
        $evaluateOption=json_decode(HlappTypeStage::getAspect($evaluate['stage']));
        $this->assign("evaluateOptions",$evaluateOption);
        $this->assign("project",$project);
        $this->assign('evaluateTemplate',$evaluateTemplate);
        $this->assign("evaluate",$evaluate);
        return $this->fetch();
    }

    /**
     * 甲方评价项目解决方案
     * @return mixed|void
     */
    public function evaSolvePage(){
        $solveId = $_GET['solveId'];
        $solveInfo = HlappProjectSolve::getSolveInfo($solveId);
        $solve = HlappProjectSolve::get($solveId);
        $this->assign("solveInfo",$solveInfo);
        $this->assign("solve",$solve);
        $evaluateInfo = $solveInfo['evaluateInfo'];
        $this->assign("evaluateInfo",json_decode($evaluateInfo,true));
        return $this->fetch();
    }

    /**
     * 甲方评价方案后的项目信息
     * @return mixed|void
     */
    public function evaSolveInfo(){
        $solveId = $_GET['solveId'];
        $solveInfo = HlappProjectSolve::getSolveInfo($solveId);
        $solve = HlappProjectSolve::get($solveId);
        $this->assign("solveInfo",$solveInfo);
        $this->assign("solve",$solve);
        $evaluateInfo = $solveInfo['evaluateInfo'];
        $this->assign("evaluateInfo",json_decode($evaluateInfo,true));
        return $this->fetch();
    }

    /**
     * 甲方对措施进行评价
     * @return mixed|void
     */
    public function evaSolve(){
        $result = Result::getResultError();
        $solveId = $_POST['id'];
        $remark = $_POST['remark'];
        $status = $_POST['status'];
        $solve = HlappProjectSolve::get($solveId);
        if ($solve && $solve->evaluateStatus == null){
            $solve->evaluateContent = $remark;
            $solve->evaluateStatus = $status;
            if ($solve->save()){
                //甲方对解决方案不满意推送给措施负责人，闭环
                if ($status == 0){
                    (new PushService())->sendUnHappyToSolve($solveId);
                    $solve->memberId;
                }
                $result = Result::getResultOk();
            }
        }else{
            $result = Result::getResultError("已经评价过了！");
        }
        return $result;
    }

    /**
     * 甲方评价
     */
    public function evaluateProject(){
        $id = $_POST['id'];
        $status= $_POST['status'];
        $_POST['evaluate_time'] = time();
        //查看项目此周此阶段是否评价过
        $evaluate = HlappProjectEvaluate::get($id);
        $week = $evaluate['week'];
        $projectId = $evaluate['projectId'];
        $e = new HlappProjectEvaluate();
        if ($week != $this->getWeekOfYear(time())){
            $result = Result::getError("评价已过期");
        }else if($evaluate->getData('status') != null){
            $result = Result::getError("此周已评价过了");
        }else{
           $e->saveOrUpdata($_POST);
           Db::table('hl_hlapp_project')->where('id', $projectId)->update(['isEvaluated'=>1]);
           if ($status==0){
               //甲方评价不满意后，将评价信息推送项目负责人
               $project = HlappProject::getProject($projectId);
               //推送区域 负责人
               if($project['manager']){$this->sendSolveToMember($projectId,$project['manager_id'],$week,$id,HlappPart::$MANAGER);}
               if($project['engineer']){$this->sendSolveToMember($projectId,$project['engineer_id'],$week,$id,HlappPart::$ENGINEER);}

               //推送 总部工程中心
               $pushCenterMembers = (new HlappMember())->where('partId','in',HlappPart::$ENGINEERING)->select();
               foreach ($pushCenterMembers as $centerMember){
                   $this->sendMessageToMember($projectId,$centerMember['id'],$week,$id,$centerMember['partId']);
               }

               //若连续三次不满意，推送项目总经理
               $evaluates = $e->where('projectId',$projectId)->order('id','desc')->limit(0,3)->select();
               $isBad=false;
               $i = 0;
               foreach ($evaluates as $item){
                   $evaStatus = $item->getData('status') ;
                   if (!is_null($evaStatus) && $evaStatus == 0){
                       $i++;
                       // 三次不满意
                       if ($i == 3){
                           $isBad = true;
                           break;
                       }
                   }
               }
               if ($isBad){
                   //推送 柏总
                   (new Open())->pushTwiceBadEvaluate($projectId);
               }
           }
           $result = Result::getOk();
        }
        return $result;
    }

    /**
     * 登记手机号
     */
    public function registPhone(){
        $phone = $_POST['telphone'];
        $m = new HlappMember();
        $member = $m->where('phone',$phone)->find();
        if($member){
            if($member['openId']){
                $r = Result::getError("您已经登记过个人信息了，不需要再次登记");
            }else{
                $memberInfo = getMember();
                $member['openId'] =$memberInfo["openid"];
                $r = Result::getOk($member->save());
            }
        }else{
            $r = Result::getError("您的信息没有录入系统，请联系工作人员录入");
        }
        return $r;
    }

    /**
     * 給  工程中心發送通知消息
     * @param $projectId
     * @param $memberId
     * @param $week
     * @param $eId
     * @param $partType
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function sendMessageToMember($projectId,$memberId,$week,$eId,$partType){
        $projectModel = new HlappProject();
        $project = $projectModel->where("id",$projectId)->find();
        $log['projectId']=$projectId;
        $log['week']=$week;
        $log['stage']=$project['stage'];
        $log['member']=$memberId;
        $log['type']=2;
        $log['eId']=$eId;
        $log['part']=$partType;
        $log['status'] = 0;
        try{
            $member = (new HlappMember())->where("id",$memberId)->find();
            $openId = $member['openId'];
            $templateId="C9_m3X7GSSY9lT8VbhWmbBmRvc_uLpjpJZRcaVRq7gU";
//            $jumpUrl=addonUrl("hlapp/Wap/solvePage",'',true,true);
//            $jumpUrl = $jumpUrl."?eid=".$eId."&partType=".$partType."&memberId=".$memberId;
            $jumpUrl = "";
            $data=[
                "first"=>["value"=>"甲方反馈不满意通知","color"=>"#173177"],
                "keyword1"=>["value"=>$project["name"],"color"=>"#173177"],
                "keyword2"=>["value"=>"第".$week."周评价不满意","color"=>"#173177"],
                "keyword3"=>["value"=>$project['amamager']['name'],"color"=>"#173177"],
                "remark"=>["value"=>"","color"=>"#173177"]
            ];
            if(!$openId){
                $log['message']= "请负责人先进行信息登记！";
            }else{
                \Log::INFO("开始推送工程中心. 评价id：".$eId."评价人Id：".$memberId);
                $result = (new PushService())->sendTemplateMessage($openId,$templateId,$jumpUrl,$data);
                if ($result->code){
                    //成功
                    $log['status'] = 1;
                }else{
                    if ($result->message){
                        $log['message'] = $result->message;
                    }else{
                        $log['message'] = '推送模板消息失败！';
                    }
                    \Log::ERROR($result->message);
                }
            }
        }catch (\Exception $e){
            \Log::ERROR("服务器异常 推送解决方案失败.  评价id:".$eId."人員id:".$memberId);
            $log['message']="服务器异常";
        }
        (new HlappEvaluateSendLogs())->saveOrUpdata($log);
    }

    /**
     * 给负责人发送解决方案消息
     * @param $projectId 项目id
     * @param $memberId 人员id
     * @param $week 一年第几周
     * @param $eId  评价id
     * @param $partType  部门id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function sendSolveToMember($projectId,$memberId,$week,$eId,$partType){
        $projectModel = new HlappProject();
        $project = $projectModel->where("id",$projectId)->find();
        $log['projectId']=$projectId;
        $log['week']=$week;
        $log['stage']=$project['stage'];
        $log['member']=$memberId;
        $log['type']=2;
        $log['eId']=$eId;
        $log['part']=$partType;
        $log['status'] = 0;
        try{
            $member = (new HlappMember())->where("id",$memberId)->find();
            $openId = $member['openId'];
            $templateId="C9_m3X7GSSY9lT8VbhWmbBmRvc_uLpjpJZRcaVRq7gU";
            $jumpUrl=addonUrl("hlapp/Wap/solvePage",'',true,true);
            $jumpUrl = $jumpUrl."?eid=".$eId."&partType=".$partType."&memberId=".$memberId;
            $data=[
                "first"=>["value"=>$project["name"]."项目评价信息反馈","color"=>"#173177"],
                "keyword1"=>["value"=>$project["name"],"color"=>"#173177"],
                "keyword2"=>["value"=>"第".$week."周评价不满意","color"=>"#173177"],
                "keyword3"=>["value"=>$project['amamager']['name'],"color"=>"#173177"],
                "remark"=>["value"=>"点击对第".$week."周评价进行反馈","color"=>"#173177"]
            ];
            if(!$openId){
                $log['message']= "请负责人先进行信息登记！";
            }else{
                \Log::INFO("开始推送区域负责人. 评价id：".$eId."评价人Id：".$memberId);
                $result = (new PushService())->sendTemplateMessage($openId,$templateId,$jumpUrl,$data);
                if ($result->code){
                    //成功
                    $log['status'] = 1;
                }else{
                    if ($result->message){
                        $log['message'] = $result->message;
                    }else{
                        $log['message'] = '推送模板消息失败！';
                    }
                    \Log::ERROR($result->message);
                }
            }
        }catch (\Exception $e){
            \Log::ERROR("服务器异常 推送解决方案失败.  评价id:".$eId."人員id:".$memberId);
            $log['message']="服务器异常";
        }
        (new HlappEvaluateSendLogs())->saveOrUpdata($log);
    }

    /**
     * 项目解决方案页面
     */
    public function solvePage(){
        $solveContent = null;
        $eid = $_GET['eid'];//甲方评价id
        $memberId = $_GET['memberId'];
        $partType = $_GET['partType'];//部门id

        $s =new HlappProjectSolve();
        $solve=$s->where('eId',$eid)
            ->where('memberId',$memberId)
            ->find();
        if ($solve){
            $solveContent = $solve['content'];
        }

        $evaluate = (new HlappProjectEvaluate())->where('id',$eid)->with('project')->find();
        $evaluateInfo=json_decode($evaluate['evaluateInfo'],true);
        $this->assign("evaluateInfo",$evaluateInfo);
        $this->assign("evaluate",$evaluate);
        $this->assign('partType',$partType);
        $this->assign('memberId',$memberId);
        $this->assign('solveContent',$solveContent);
        return $this->fetch();
    }

    /**
     * 添加解决方案
     */
    public function addSolve(){
        $r = Result::getError();
        $memberId = $_POST['memberId'];
        $content = $_POST['content'];
        $s =new HlappProjectSolve();
        $solve=$s->where('eId',$_POST['eId'])
            ->where('memberId',$memberId)
            ->find();
        if ($solve && $solve['checkStatus'] == 1){
            $r = Result::getError("方案已通过,勿重复提交！");
        }else{
            if ($solve){
                $s_id = $solve['id'];
                $solve->content = $content;
                $solve->checkStatus = null;
                $solve->save();
            }else{
                $s_id = $s->saveOrUpdata($_POST);
            }
            if ($s_id){
                $pushService = new PushService();
                //工程中心负责人
                $members = (new HlappMember())->where('partId',HlappPart::$ENGINEERING)->select();
                foreach ($members as $member){
                    $pushService->sendSolveToEngineer($s_id,$member['openId']);
                }
                $r = Result::getOk();
            }
        }
        return $r;
    }

    /**
     * 审核解决方案页面
     * @return mixed|void
     */
    public function examSolve(){
        $solveId = $_GET['solveId'];
        $solveInfo = HlappProjectSolve::getSolveInfo($solveId);
        $this->assign("solveInfo",$solveInfo);
        $evaluateInfo = $solveInfo['evaluateInfo'];
        $this->assign("evaluateInfo",json_decode($evaluateInfo,true));
        return $this->fetch();
    }

    /**
     * 审核项目
     */
    public function exam()
    {
       $reslut = Result::getResultError();
       $solveId = $_POST['solveId'];
       $status = $_POST['status'];
       $solve = HlappProjectSolve::get($solveId);

       $memberInfo = getMember();
       $openId =$memberInfo["openid"];
       $m =  (new HlappMember())->where('openId',$openId)->find();
       if ($m && $m['id']){
           $solve->checkMemberId = $m['id'];
       }
       if ($status){
           //通过审核
           if ($solve->checkStatus == null){
               $solve->checkStatus = 1;
               if ($solve->save()){
                   $reslut->setCode(1);
                   $reslut->setMessage("成功");
                   $reslut->setResult(1);//通过审核标志
               }
           }else{
               $reslut->setMessage("该项目已审核过");
           }
       }else{
           //审核驳回
           if ($solve->checkStatus === null){
               $solve->checkStatus = 0;
               if ($solve->save()){
                   $reslut->setCode(1);
                   $reslut->setMessage("成功");
                   $reslut->setResult(0);//未通过审核标志
               }
           }else{
               $reslut->setMessage("该项目已审核");
           }
       }

       return $reslut->toJson();
    }

    /**
     * 审核失败打回
     */
    public function sendSolveBack(){
        $solveId = $_POST['solveId'];
        $result = (new PushService())->sendSolveBack($solveId);
        return Result::objestToJson($result);
    }

    /**
     * 审核通过的方案推送给甲方
     */
    public function sendSolveToA(){
        $solveId = $_POST['solveId'];
        $result = (new PushService())->sendSolve2A($solveId);
        return Result::objestToJson($result);
    }
}